#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import cgi
import json
import db_conf
import metabobase_util

con = None

try:
    qform = cgi.FieldStorage()
    search_input = qform.getvalue('search_input')
    unassigned = qform.getvalue('only_unassigned')
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config)) 
    cur = con.cursor()
    #default select if no filtering is set
    select_s = "select chromatogram_id, proprietary_path from chromatogram where upper(proprietary_path) like upper('%" + search_input + "%')"
    if (unassigned == 'T'):
	select_s = "select chromatogram_id, proprietary_path FROM chromatogram LEFT JOIN chromatogram_sample_group csg USING(chromatogram_id) WHERE upper(proprietary_path) LIKE upper('%" + search_input + "%') AND csg.experiment_id IS NULL"

    cur.execute(select_s)          
    rows = cur.fetchall()    
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    pa['aaData'] = []
    for row in rows:
	pi = []
	for r in range(len(row)):
		if (r == 1):
			tk = row[r].split("/")
			legitpath = tk[len(tk)-5:]
			pi.append("/".join(legitpath))
		else:
			pi.append(str(row[r]))
        pa['aaData'].append(pi)	
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    
    if con:
        con.close()
